// 01home/home.js
var app = getApp()
var co = require('../../js/common.js')
var ws = require('../../js/websocket.js')
var MAP = require('../../js/map.js')
var pKeys = ['latitude', 'longitude']//position的keys
var _this    //指this
var map     //地图参数
Page({
   data: {
      p: app.aData.p,
      markers: [],
      ctrls: [],
      mapHeight: 0,
      addressBar: '',
      avatarUrl: ''
   },

   onLoad: function (opt) {
      //【1】创建地图组件对象
      this.mapObj = wx.createMapContext('masterMap')
      //【2】初始化地图：大小、masker控件
      this.initMap()

      this.switchChangeMode()    //【5.3】初始化所有控件
      //【3】处理转发参数opt
      this.handleOpt(opt)
      //【4】移到并获取地图中心
      this.moveAndGetMapCenter()

      _this = this

      app.setHomePageShowAvatarUrlNotice(function (res) {
         console.log('【首页收到通知】res', res)
         _this.setData({ avatarUrl: res })
      })
   },
   //【3】处理转发参数opt
   handleOpt: function (opt) {
      console.log('【转发小程序传参】opt', opt)
      if (opt.inviter_uid) {
         app.aData.inviter = opt
      }
   },
   //【4】移到并获取地图中心
   moveAndGetMapCenter: function () {
      MAP.moveAndGetMapCenter(this.mapObj, function (res) {
         console.log('【移到并获取地图中心】res', res)
         var loc = co.addValueForKey({}, res, pKeys)//只取经纬度
         app.aData.p = loc          //存app全局坐标
         _this.getUserInfo()         //【5】获取用户信息
         _this.setData({ p: loc })   //存本页数据
         _this.getLocationName(res)  //【6】获取中文地址并显示
      })
   },
   //【5】获取用户信息(新)
   getUserInfo: function () {
      var userInfo = wx.getStorageSync('userInfo')
      if (userInfo.hasOwnProperty('identity')) {
         _this.setData({ avatarUrl: userInfo.avatarUrl })
         this.loginedSetData(userInfo, 'login')
      } else {
         app.getUserInfo(function (res) {
            console.log('【getUserInfo】', res)
            if (res.data.hasOwnProperty('identity')) {
               _this.loginedSetData(res.data, res.msg)
            }
            if (co.empty(_this.data.avatarUrl)) {
               _this.setData({ avatarUrl: res.data.avatarUrl })
            }
         })
      }
   },
   //【5.1】获取后设置用户信息
   loginedSetData: function (info, _type) {
      app.saveUserLog(info)     //【5.2】保存日志
      app.aData.userInfo = info
      app.aData.mode = info.identity == 'master' ? 'master' : 'order'
      this.getNearby()           //【5.4】初始化标记markers
      info.type = _type
      ws.initWebsocket(info, 29354, function (res) {
         console.log('【初始化socket、登录成功并回调】', res)
         _this.onSocketMsg()
      })
   },
   //【5.3】切换模式
   switchChangeMode: function () {
      app.aData.mode = app.aData.mode == 'master' ? 'order' : 'master'
      this.setData({ ctrls: this.initCtrls(map) })
      wx.setNavigationBarTitle({
         title: app.aData.mode == 'master' ? '找师傅' : '找订单',
      })
      this.getNearby()
   },
   //【5.4】获取附近维修师傅
   getNearby: function (loc) {
      var param = loc ? loc : this.data.p
      console.log('【自已信息app.aData.userInfo】', app.aData.userInfo)
      console.log('【重新获取getNearby:param】', param)
      if (app.aData.mode == 'master') {
         param.appid = app.aData.app.appid
         param.identity = 'master'
         co.getShareApi('user/mg/getMasterList', param, function (res) {
            _this.setData({ markers: res.data })
         })
      } else {
         co.getSelfApi('order/mg/getNearbyList', param, function (res) {
            _this.setData({ markers: res.data })
         })
      }
   },
   //【6】调用坐标转中文地址
   getLocationName: function (loc) {
      MAP.getLocationName(loc, function (address) {
         console.log('【坐标转中文地址】' + loc.latitude + '，' + loc.longitude + '==' + address)
         _this.updateAddresBar(address)
      })
   },
   //【6.1】更新地址栏信息
   updateAddresBar: function (address, mark) {
      this.setData({
         addressBar: mark ? '' : address,
         master: mark ? '师傅昵称：' + mark.callou.content + '\n登记位置：' + address : '',
         avatarUrl: mark ? mark.avatarUrl : app.aData.userInfo.avatarUrl
      })
   },

   onReady: function () {
      console.log('【渲染进入：onReady，全局变量app.aData，注意转发被点进入时的】', app.aData)
   },

   sendToMyInviterList: function (info) {
      var keys = ['avatarUrl', 'nickName', 'time', 'inviter_id']
      var msg = co.addValueForKey({}, info, keys)
      ws.sendToAll(msg, function (cb) {
         console.log('【邀请到的人发送成功】', cb)
      })
   },

   onSocketMsg: function () {
      ws.onSocketMsg(function (res) {
         console.log('【home.js收到监听socket回调】', res)
         if (res.type == 'notice') {
            var distance_x = Math.abs(res.latitude - app.aData.p.latitude)
            var distance_y = Math.abs(res.longitude - app.aData.p.longitude)
            if (distance_x <= 0.1 && distance_y <= 0.1) {
               var markers = _this.data.markers
               res.id = markers.length                //不用加1
               delete res.type
               markers.push(res)
               _this.setData({
                  markers: markers,                   //新增marker,刷新界面
                  p: co.addValueForKey({}, res, pKeys)//更新位置，移到中心
               })
               if (res.creator_uid != app.aData.userInfo.unionid) {
                  app.playMp3('http://img.ls293.cc/repair/mp3/niyouxindingdan_master.mp3')
               }
            }
         }
      })
   },
   //【2】初始化地图
   initMap: function () {
      var sys = wx.getSystemInfoSync()
      console.log('【手机型号参数】', sys)
      var offset_h = 112 + 50
      if (sys.platform == 'android') {
         offset_h = 172
      } else if (sys.platform == 'ios') {
         offset_h = 112 + 50
      }
      // co.modal('h=' + h + ',ww=' + sys.windowWidth + ',wh=' + sys.windowHeight + ',sw=' + sys.screenWidth + ',sh=' + sys.screenHeight + ',brand=' + sys.brand + ',platform=' + sys.platform)
      map = {
         width: sys.windowWidth,
         height: sys.screenHeight - offset_h,//260,//
         centerCtrlWidth: 40,
         centerCtrlHeight: 40,
      }
      map.centerCtrlLeft = (map.width - map.centerCtrlWidth) / 2
      map.centerCtrlTop = map.height / 2 - map.centerCtrlHeight

      this.setData({ mapHeight: map.height })
      console.log('【地图初始化完成this.data】', this.data)
   },
   //点击地图标签
   markerTap: function (e) {
      var mark = this.data.markers[e.markerId]
      if (app.aData.mode == 'master') {
         MAP.getLocationName(co.getLoc(mark), function (address) {
            _this.updateAddresBar(address, mark)
         })
      } else {
         wx.navigateTo({
            url: '/home/04order/detail?order_id=' + mark.order_id
         })
      }
   },
   //跳转到我
   toMe: function () {
      wx.switchTab({ url: '/pc/01personCenter/personCenter' })
   },
   //地图视野变化时触发
   mapChange: function (e) {
      if (e.type == 'end') {
         this.getMapCenterAndNearbyMarkers()
      } else {
         console.log('【地图变化】', e)
      }
   },
   //获取地图中心及重新获取附近师傅
   getMapCenterAndNearbyMarkers: function () {
      MAP.getMapCenterAddress(this.mapObj, function (loc) {
         // if (app.aData.userInfo.identity) {
         _this.getNearby(loc)//重新获取附近的师傅或订单
         // }
         _this.getLocationName(loc)
      })
   },
   //点击控件事件
   ctrlEvent: function (e) {
      console.log('【点中控件】', e)
      var e_id = e.controlId
      if (e_id == 'toUserLoc') {
         this.mapObj.moveToLocation()
      } else if (e_id == 'call') {
         if (app.aData.userInfo.user_id) {
            wx.navigateTo({ url: '../02callMaster/callMaster' })
         } else {
            wx.navigateTo({ url: '../../login/login' })
         }
      } else if (e_id == 'switch') {
         this.switchChangeMode()
      }
   },
   //分享
   onShareAppMessage: function () {
      var urlParam = ''
      if (app.aData.userInfo.openid) {
         urlParam = '?inviter_oid=' + app.aData.userInfo.openid + '&inviter_uid=' + app.aData.userInfo.unionid
      }
      var share = {
         title: '【门业维修共享平台】',
         path: '/home/01homePage/home' + urlParam
      }
      console.log('【分享】share', share)
      return share
   },
   //初始化地图控件
   initCtrls: function (map) {
      //间距，回原点图宽，呼叫按钮宽高
      console.log('【进来了initCtrls】')
      var space = 10, to_w = 40, call_h = 40, switch_h = 30
      var switchBtn = '/img/switch_' + app.aData.mode + '.png'
      return [
         {
            id: 'centerMark',
            iconPath: '/img/selected.png',
            position: {
               left: map.centerCtrlLeft,
               top: map.centerCtrlTop,
               width: map.centerCtrlWidth,
               height: map.centerCtrlHeight
            },
            clickable: true
         },
         {
            id: 'toUserLoc',
            iconPath: '/img/to_user_location.png',
            position: {
               left: space,
               top: map.height - (space + 5) - to_w,
               width: to_w,
               height: to_w,
            },
            clickable: true
         },
         {
            id: 'call',
            iconPath: '/img/call_master.png',
            position: {
               left: (map.width - call_h * 4) / 2,
               top: map.height - (space + 5) - call_h,
               width: call_h * 4,
               height: call_h,
            },
            clickable: true
         },
         {
            id: 'switch',
            iconPath: switchBtn,
            position: {
               left: map.width - switch_h * 2.1 - 10,
               top: 10,
               width: switch_h * 2.1,
               height: switch_h,
            },
            clickable: true
         }
      ]

      console.log('【进来了initCtrls尾】')
   },
})